package cn.fzkj.helper;

import cn.fzkj.config.OssProperties;
import cn.fzkj.file.FilePathDescriptor;
import cn.fzkj.model.UploadResult;
import cn.fzkj.utils.FileUploadUtils;
import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author mr
 * @description
 * @since 2024/4/30
 */
public class LocalFileHelper implements FileHelper {
    private final Logger log = LoggerFactory.getLogger(LocalFileHelper.class);

    private final OssProperties.LocalConf localConf;

    public LocalFileHelper(OssProperties.LocalConf localConf) {
        this.localConf = localConf;
    }

    @Override
    public UploadResult upload(MultipartFile file) {
        try {
            // 上传
            FilePathDescriptor pathDescriptor = FileUploadUtils.upload(localConf.getPath(), file);

            UploadResult uploadResult = new UploadResult();
            uploadResult.setFilePath(pathDescriptor.getFullPath());
            uploadResult.setFileName(pathDescriptor.getName());
            uploadResult.setKey(pathDescriptor.getRelativePath());
            uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
            uploadResult.setSize(file.getSize());
            uploadResult.setSuffix(pathDescriptor.getExtension());

            handleImageMetadata(file, uploadResult, pathDescriptor::getFullPath);
            return uploadResult;
        } catch (Exception e) {
            log.error("upload file to local storage failed, file: {}", file.getOriginalFilename(), e);
            throw new RuntimeException("上传文件到本地失败，file: " + file.getOriginalFilename());
        }
    }

    @Override
    public void delete(@NonNull String key) {
        try {
            boolean success = Files.deleteIfExists(Paths.get(localConf.getPath(), key));
            log.info("delete location {}'s key: {} {}.", localConf.getPath(), key, success ? "success" : "failed");
        } catch (IOException e) {
            log.warn("delete local storage failed, location: {}, key: {}", localConf.getPath(), key, e);
        }
    }
}
